package com.xjy.ftpmanagment.action;

import java.sql.Timestamp;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Random;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.sun.org.apache.regexp.internal.REUtil;
import com.xjy.common.action.BaseAction;
import com.xjy.common.util.DateUtil;
import com.xjy.common.util.EncryptionUtil;
import com.xjy.common.util.MailUtil;
import com.xjy.common.util.PageBean;
import com.xjy.ftpmanagment.pojo.FtpUser;
import com.xjy.ftpmanagment.pojo.SysParam;
import com.xjy.ftpmanagment.pojo.SysUser;
import com.xjy.ftpmanagment.service.FtpManagmentService;
import com.xjy.ftpmanagment.util.Page;
import com.xjy.ftpmanagment.util.SessionUtil;

import org.apache.log4j.Logger;
import org.aspectj.weaver.ast.Var;
@SuppressWarnings("all")
public class FtpManagmentAction extends BaseAction{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static org.apache.log4j.Logger logger=Logger.getLogger(FtpManagmentAction.class);
	private FtpManagmentService ftpManagmentService;
	public String getExpiration() {
		return expiration;
	}
	public void setExpiration(String expiration) {
		this.expiration = expiration;
	}
	private String expiration;
	public FtpManagmentService getFtpManagmentService() {
		return ftpManagmentService;
	}
	public void setFtpManagmentService(FtpManagmentService ftpManagmentService) {
		this.ftpManagmentService = ftpManagmentService;
	}
	public String parameter(){
		return Page.PARAMETER;
	}
	public String log(){
		return Page.LOG;
	}

	/**
	 * 添加或修改默认收件人
	 * @return
	 */
	public String receiverMaintain(){
		JSONObject jRequest=getJsonObjectByRequestData();
		long id=-1;
		try {
			id=jRequest.getLong("id");
		} catch (JSONException e) {
		}
		SysUser sysUser=null;
		if(id!=0){
			List<SysUser> sysUsers=this.ftpManagmentService.getSysUsers(" id=? and system!=0", new Object[]{id});
			if(sysUsers!=null&&sysUsers.size()>0){
				sysUser=sysUsers.get(0);
			}
		}
		JSONObject jResult=new JSONObject();
		try {
			jResult.put("id",sysUser==null?"0":sysUser.getId());
			jResult.put("name", sysUser==null?"":sysUser.getUsername());
			jResult.put("mail", sysUser==null?"":sysUser.getMail());
			jResult.put("description", sysUser==null?"":sysUser.getDescription());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		responseData=jResult.toString();
		return Page.MAIL_RECEIVER_MAINTAIN;
	}
	public String deleteSysUsers(){
		JSONObject jRequest=getJsonObjectByRequestData();
		String ids=null;
		try {
			ids=jRequest.getString("ids");
		} catch (JSONException e) {
		}
		if(ids!=null){
			String id[]=ids.split(",");
			if(id!=null && id.length>0){
				long []deleteIds=new long[id.length];
				for(int i=0;i<id.length;i++){
					deleteIds[i]=Long.valueOf(id[i]);
				}
				this.ftpManagmentService.deleteSysUsers(deleteIds);
			}
		}
		return this.mailReceiver();
	}
	/**
	 * 保存收件人
	 * @return
	 */
	public String saveReceiver(){
		JSONObject jRequest=getJsonObjectByRequestData();
		long id=-1;
		SysUser sysUser=null;
		try {
			id=jRequest.getLong("id");
			if(id<1){
				sysUser=SysUser.create();
			}else{
				sysUser=new SysUser();
				sysUser.setId(id);
			}
			sysUser.setUsername(jRequest.getString("name"));
			sysUser.setMail(jRequest.getString("mail"));
			sysUser.setDescription(jRequest.getString("description"));
		} catch (JSONException e) {
			e.printStackTrace();
		}
		if(null!=sysUser){
			this.ftpManagmentService.saveOrUpdateSysUser(sysUser);
		}
		return mailReceiver();
	}
	public String mailReceiver(){
		List<SysUser> sysUsers=this.ftpManagmentService.getSysUsers(" system!=0", null);
		pageBean=PageBean.packagePageBean(0, 0, sysUsers, 0);
		return Page.MAIL_RECEIVER;
	}
	/**
	 * 其它设置，包含发送邮件、存放目录、有效期设置
	 * @return
	 */
	public String otherSetting(){
		List<SysParam> sysParams=this.ftpManagmentService.getSysParams(null, null);
		JSONArray result=new JSONArray();
		try{
			for(SysParam sysParam:sysParams){
				JSONObject object=new JSONObject();
				object.put("id", sysParam.getId());
				object.put("v1", sysParam.getV1());
				object.put("v2", sysParam.getV2());
				object.put("v3", sysParam.getV3());
				object.put("v4", sysParam.getV4());
				result.put(object);
			}
		}catch (Exception e) {
			logger.error("获取系统参数设置中其它设置选项中参数出错！"+e.getMessage());
		}
		responseData=result.toString();
		return Page.OTHER_SETTING;
	}
	/**
	 * 保存其它设置中相关参数
	 */
	public void saveOtherSetting(){
		JSONObject jRequest=getJsonObjectByRequestData();
		List<SysParam> sysParams=new ArrayList<SysParam>();
		try {
			SysParam sysParam=new SysParam();
			JSONObject object=jRequest.getJSONObject("saveDays");
			sysParam.setId(object.getLong("id"));
			sysParam.setV1(object.getString("v1"));
			sysParams.add(sysParam);
			sysParam=null;
			sysParam=new SysParam();
			object=jRequest.getJSONObject("normalSavePath");
			sysParam.setId(object.getLong("id"));
			sysParam.setV1(object.getString("v1"));
			sysParams.add(sysParam);
			sysParam=null;
			sysParam=new SysParam();
			object=jRequest.getJSONObject("tempSavePath");
			sysParam.setId(object.getLong("id"));
			sysParam.setV1(object.getString("v1"));
			sysParams.add(sysParam);
			sysParam=null;
			sysParam=new SysParam();
			object=jRequest.getJSONObject("mail");
			sysParam.setId(object.getLong("id"));
			sysParam.setV1(object.getString("v1"));
			sysParam.setV2(object.getString("v2"));
			sysParam.setV3(object.getString("v3"));
			sysParam.setV4(object.getString("v4"));
			sysParams.add(sysParam);
			
		} catch (JSONException e) {
			logger.error("解析JSON数据出错，错误代码："+e.getLocalizedMessage());
		}
		
		String result="1";
		try {
			this.ftpManagmentService.saveSysParams(sysParams);
		} catch (Exception e) {
			result="-1";
			logger.error("保存其它设置数据出错，错误代码："+e.getLocalizedMessage());
		}
		JSONObject jResult=new JSONObject();
		try {
			jResult.put("result", result);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		writeJson(jResult.toString());
	}
	public String createFtpUser(){
		JSONObject jResult=new JSONObject();
		try {
			jResult.put("minDate", DateUtil.getTime(1));
		} catch (JSONException e) {
			
		}
		responseData=jResult.toString();
		return Page.CREATE_FTP_USER;
	}
	public void genePass(){
		char[] arrChar = new char[]{
				   'a','b','d','c','e','f','g','h','i','j','k','l','m','n','p','r','q','s','t','u','v','w','z','y','x',
				   '0','1','2','3','4','5','6','7','8','9'
		};
		StringBuilder num = new StringBuilder();
		Random rnd = new Random(Calendar.getInstance().getTimeInMillis());
		for (int i = 0; i < 6; i++){
			num.append(arrChar[rnd.nextInt(arrChar.length)]);
		}
		writeHtml(num.toString());
	}
	public void checkUser(){
		JSONObject jRequest=getJsonObjectByRequestData();
		String ftpUserName=null;
		if(jRequest!=null){
			try {
				ftpUserName=jRequest.getString("ftpUserName");
			} catch (JSONException e) {
			}
		}
		int count=-1;
		if(null!=ftpUserName){
			count=this.ftpManagmentService.getCount("ftpUserName=?", new Object[]{ftpUserName.trim()});
		}
		writeHtml(String.valueOf(count));
	}
	public String ftpUserList() throws ParseException{
		if(pageSize<1){
			pageSize=8;
		}
		pageBean=null;
		if(expiration!=null && !expiration.trim().equals("")){
			pageBean=this.ftpManagmentService.getFtpUsers(page, pageSize, "expiration<=? and expiration!='1980-1-1'", new Object[]{DateUtil.YMD.parse(expiration)}, null);
		}else{
			pageBean=this.ftpManagmentService.getFtpUsers(page, pageSize, null, null, null);
		}
		
		return Page.FTP_USER_LIST;
	}
	public void ajaxSaveFtpUser() throws ParseException{
		JSONObject jRequest=getJsonObjectByRequestData();
		String username=null,password=null,usertype=null,noticetype=null,tempDate=null,mailReceiver=null;
		try {
			username=jRequest.getString("username");
			password=jRequest.getString("password");
			usertype=jRequest.getString("usertype");
			noticetype=jRequest.getString("noticetype");
			tempDate=jRequest.getString("tempDate");
			mailReceiver=jRequest.getString("mailReceiver");
		} catch (JSONException e) {
		}
		boolean resultSave=this.ftpManagmentService.saveFtpUser(username, password, usertype, noticetype, tempDate, mailReceiver);
		String result="0";
		if(resultSave){
			SysParam mailSysParam=this.ftpManagmentService.getSysParams("id=?", new Object[]{1l}).get(0);
			List<SysUser> sysUsers=this.ftpManagmentService.getSysUsers(" system!=0", null);
			List<String> mailList=new ArrayList<String>();
			for(SysUser sysUser :sysUsers){
				if(sysUser.getMail()!=null && sysUser.getMail().trim().length()>0){
					mailList.add(sysUser.getMail());
				}
			}
			
			boolean resultMail=MailUtil.sentMail(mailSysParam, null, mailList, username+" 任务单ID及密码","FTP地址：ftp.ceode.ac.cn (ftp://159.226.224.8)" +
					"          账号："+username+"           密码："+password);
			if(!resultMail){
				result="-2";//邮件发送失败
			}
		}else{
			result="-1";//用户保存失败，请检查用户名是否存在非法字符
		}
		writeHtml(result);
	}
	public String deleteFtpUser() throws ParseException{
		JSONObject jRequest=getJsonObjectByRequestData();
		String ids=null;
		try {
			ids=jRequest.getString("ids");
		} catch (JSONException e) {
		}
		if(ids!=null){
			String id[]=ids.split(",");
			if(id!=null && id.length>0){
				int []deleteIds=new int[id.length];
				for(int i=0;i<id.length;i++){
					deleteIds[i]=Integer.valueOf(id[i]);
				}
				this.ftpManagmentService.deleteFtpUsers(deleteIds);
			}
		}
		return this.ftpUserList();
	}
	public String saveFtpUser() throws ParseException{
		String userID=SessionUtil.getSession().get("userID").toString();
		if(userID!=null && !userID.trim().equals("")){
			if(userID.trim().toLowerCase().equals("admin")){
				return ftpUserList();
			}
		}
		return createFtpUser();
	}
}
